import { log } from '@hypothesis/frontend-build';
import { vitestCoverageOptions } from '@hypothesis/frontend-testing/vitest';
import { babel } from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import { nodeResolve } from '@rollup/plugin-node-resolve';

export const excludeFromCoverage = [
  '**/node_modules/**',
  '**/test/**/*.js',
  '**/tests/**/*.js',
  '**/test-util/**',
  '**/index.{ts,tsx}',
  '**/login-forms.tsx',
  '**/group-forms.tsx',
];

export default {
  input: 'build/scripts/test-inputs.js', // Input file generated by gulp task
  output: {
    file: 'build/scripts/tests.bundle.js',
    format: 'es',
    sourcemap: true,

    // Simplify build output by putting all code in one bundle.
    inlineDynamicImports: true,
  },
  treeshake: false,
  // Suppress a warning (https://rollupjs.org/guide/en/#error-this-is-undefined)
  // due to https://github.com/babel/babel/issues/9149.
  //
  // Any code string other than "undefined" which evaluates to `undefined` will work here.
  context: 'void(0)',
  plugins: [
    nodeResolve({
      browser: true,
      extensions: ['.js', '.ts', '.tsx'],

      // Disallow use of browser polyfills for Node builtin modules. We're
      // trying to avoid dependencies which rely on these.
      //
      // There are a couple of references to Node builtins that are stubbed by
      // configuration for the `virtual` plugin above.
      preferBuiltins: false,
    }),
    commonjs({
      include: 'node_modules/**',
    }),
    babel({
      babelHelpers: 'bundled',
      exclude: 'node_modules/**',
      extensions: ['.js', '.ts', '.tsx'],
      presets: [
        [
          '@babel/preset-react',
          {
            // Turn off the `development` setting in tests to prevent warnings
            // about `this`. See https://github.com/babel/babel/issues/9149.
            development: false,
            runtime: 'automatic',
            importSource: 'preact',
          },
        ],
      ],
      plugins: [
        'mockable-imports',
        [
          'babel-plugin-istanbul',
          {
            ...vitestCoverageOptions,
            exclude: excludeFromCoverage,
          },
        ],
      ],
    }),
  ],
  onwarn: warning => {
    // Suppress security warning about `eval` usage in syn, a test-only
    // dependency.
    if (warning.id.includes('node_modules/syn/') && warning.code === 'EVAL') {
      return;
    }
    log.warn(`Rollup warning: ${warning} (${warning.url})`);
  },
};
